<?php

namespace app\erp\model;

use app\jun\controller\Api;
use think\Model;
use traits\model\SoftDelete;
use think\Cache;
use think\Db;

class Invoicedb extends Model
{
    use SoftDelete;

    public $param = array();
    protected $name = 'invoice';
    protected $pk = 'invoice_id';
    protected $type = [
        'create_time' => 'timestamp:Y-m-d H:i',
        'delete_time' => 'timestamp:Y-m-d H:i',
        'invoice_time' => 'timestamp:Y-m-d H:i',
        'post_time' => 'timestamp:Y-m-d H:i',
        'receive_time' => 'timestamp:Y-m-d H:i',
        'draw_time' => 'timestamp:Y-m-d H:i'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;
    protected $insert = [
        'partner_id' => PARTNER_ID,
        'site_id',
        'state' => 1
    ];

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr ['partner_id'] = PARTNER_ID;
        if (!isset ($new_arr ['site_id'])) {
            $new_arr ['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    protected function setSiteIdAttr($value)
    {
        if (!$value) {
            return SITE_ID;
        }
        if ($value == 0) {
            return null;
        }
        return $value;
    }

    public function setCartIdsAttr($value)
    {
        if (is_array($value)) {
            return implode(',', $value);
        } else {
            return $value;
        }
    }

    public function setOrderNosAttr($value)
    {
        if (is_array($value)) {
            return implode(',', $value);
        } else {
            return $value;
        }
    }

    public function scopeOrderNo($query, $order_no)
    {
        if (is_array($order_no)) {
            $temp = $order_no;
        } else {
            $temp = explode(',', $order_no);
        }
        if (count($temp) == 1) {
            $query->where('order_nos', $order_no);
        } else {
            $query->where('', 'exp', 'find_in_set(`order_nos`,"' . $temp . '")');
        }
    }

    public function scopeMemberId($query, $member_id)
    {
        $query->where('member_id', $member_id);
    }

    public function scopeInvoiceId($query, $invoice_id)
    {
        $query->where('invoice_id', $invoice_id);
    }

    public function scopeApplyState($query, $apply_state)
    {
        $query->where('apply_state', $apply_state);
    }

    public function scopeState($query, $state)
    {
        if (is_array($state)) {
            $query->where('state', 'IN', $state);
        } else {
            $query->where('state', $state);
        }
    }

    public function scopeBuilderType($query, $builder_type)
    {
        $query->where('builder_type', $builder_type);
    }

    public function scopeInvoiceTitle($query, $invoice_title)
    {
        $query->where('invoice_title', 'like', '%' . $invoice_title . '%');
    }

    public function scopeInvoiceDuty($query, $invoice_duty)
    {
        $query->where('invoice_duty', 'like', '%' . $invoice_duty . '%');
    }

    public function scopeDrawState($query, $draw_state)
    {
        $query->where('draw_state', $draw_state);
    }

    public function scopePostState($query, $post_state)
    {
        $query->where('post_state', $post_state);
    }

    public function scopeReceiveState($query, $receive_state)
    {
        $query->where('receive_state', $receive_state);
    }

    public function scopeIsInvoice($query, $is_invoice)
    {
        $query->where('is_invoice', $is_invoice);
    }

    public function getInvoiceProofsAttr($value, $data)
    {
        if ($data['invoice_proof']) {
            $uploaddb = new Uploaddb();
            $get_upload = $uploaddb->find($data['invoice_proof']);
            if (!strstr($get_upload['save_path'], 'http')) {
                $get_upload ['save_path'] = $_SERVER ['REQUEST_SCHEME'] . '://' . $_SERVER ['HTTP_HOST'] . '/uploads/' . $get_upload ['save_path'];
            }
            return $get_upload['save_path'];
        }
    }

    // 基础查询
    public function base($query)
    {
        $field = $this->getDeleteTimeField(true);
        if ($field) {
            if (isset ($this->param ['delete']) && $this->param ['delete'] == 'yes') {
                $this->onlyTrashed();
            } else {
                $query->useSoftDelete($field);
            }
        }
        /*$query->where('partner_id', PARTNER_ID);
        if (isset ($this->param ['site_id'])) {
            if ($this->param ['site_id'] == 0 || $this->param ['site_id'] == '') {
                $query->where('site_id', null);
            } elseif ($this->param ['site_id'] != -1) {
                $query->where('site_id', $this->param ['site_id']);
            }
        } else {
            if (!empty (SITE_ID)) {
                $query->where('site_id', SITE_ID);
            } else {
                $query->where('site_id', null);
            }
        }*/
        if (isset ($this->param ['order_no']) && $this->param ['order_no']) {
            $query->orderNo($this->param ['order_no']);
        }
        if (isset ($this->param ['order_nos']) && $this->param ['order_nos']) {
            $query->orderNo($this->param ['order_nos']);
        }
        if (isset ($this->param ['member_id']) && $this->param ['member_id']) {
            $query->memberId($this->param ['member_id']);
        }
        if (isset ($this->param ['invoice_id']) && $this->param ['invoice_id']) {
            $query->invoiceId($this->param ['invoice_id']);
        }
        if (isset ($this->param ['apply_state']) && $this->param ['apply_state']) {
            $query->applyState($this->param ['apply_state']);
        }
        if (isset ($this->param ['state']) && $this->param ['state']) {
            $query->state($this->param ['state']);
        }
        if (isset ($this->param ['builder_type']) && $this->param ['builder_type']) {
            $query->builderType($this->param ['builder_type']);
        }
        if (isset ($this->param ['invoice_title']) && $this->param ['invoice_title']) {
            $query->invoiceTitle($this->param ['invoice_title']);
        }
        if (isset ($this->param ['invoice_duty']) && $this->param ['invoice_duty']) {
            $query->invoiceDuty($this->param ['invoice_duty']);
        }
        if (isset ($this->param ['draw_state']) && $this->param ['draw_state']) {
            $query->drawState($this->param ['draw_state']);
        }
        if (isset ($this->param ['post_state']) && $this->param ['post_state']) {
            $query->postState($this->param ['post_state']);
        }
        if (isset ($this->param ['receive_state']) && $this->param ['receive_state']) {
            $query->receiveState($this->param ['receive_state']);
        }
        if (isset ($this->param ['is_invoice']) && $this->param ['is_invoice']) {
            $query->isInvoice($this->param ['is_invoice']);
        }
        if (isset ($this->param ['gys_state']) && $this->param ['gys_state']) {
            $query->gysState($this->param ['gys_state']);
        }
        if (isset ($this->param ['order_shoukuan']) && $this->param ['order_shoukuan']) {
            $query->orderShoukuan($this->param ['order_shoukuan']);
        }
        if (isset ($this->param ['order_fukuan']) && $this->param ['order_fukuan']) {
            $query->orderFuKuan($this->param ['order_fukuan']);
        }
        if (isset ($this->param ['susername']) && $this->param ['susername']) {
            $query->susername($this->param ['susername']);
        }
        if (isset($this->param['supplier_picture']) && $this->param['supplier_picture']) {
            $query->supplierPicture($this->param['supplier_picture']);
        }
    }

    public function scopeSupplierPicture($query, $supplier_picture)
    {
        $memberdb = new Memberdb();
        if ($supplier_picture == 1) {
            $get_member_ids = $memberdb->whereNotNull('supplier_picture')->where('site_id', 117)->where('is_supplier', 1)->column('member_id');
        } else {
            $get_member_ids = $memberdb->whereNull('supplier_picture')->where('site_id', 117)->where('is_supplier', 1)->column('member_id');
        }
        $orderdb = new Orderdb();
        $get_order_nos = $orderdb->whereIn('supplier_id', $get_member_ids)->column('order_no');
        $query->whereIn('order_nos', $get_order_nos);
    }

    public function scopeSusername($query, $susername)
    {
        $get_supplier_data = Db::table('__MEMBER__')
            ->alias('m')->where('m.supplier_name', 'like', '%' . $susername . '%')
            ->where('m.is_supplier', 1)
            ->join('__ORDER__ o', 'm.member_id = o.supplier_id')
            ->field('o.order_no')
            ->select();
        if (!$get_supplier_data->isEmpty()) {
            $order_nos = array();
            foreach ($get_supplier_data as $key => $val) {
                array_push($order_nos, $val ['order_no']);
            }
            $query->where('order_nos', 'IN', $order_nos);
        } else {
            $query->where('order_nos', '-1');
        }
    }

    public function scopeOrderShoukuan($query, $order_shoukuan)
    {
        if (is_array($order_shoukuan)) {
            $query->where('order_shoukuan', 'IN', $order_shoukuan);
        } else {
            $query->where('order_shoukuan', $order_shoukuan);
        }
    }

    public function scopeOrderFukuan($query, $order_fukuan)
    {
        if (is_array($order_fukuan)) {
            $query->where('order_fukuan', 'IN', $order_fukuan);
        } else {
            $query->where('order_fukuan', $order_fukuan);
        }
    }

    public function scopeGysState($query, $gys_state)
    {
        $query->where('gys_state', $gys_state);
    }

    public function ajaxFind()
    {
        $data = $this->master()->order('invoice_id desc')->find();
        if ($data) {
            if (!isset ($this->param ['no_need_invoice_handle'])) {
                $data = $this->handleData($data->toArray());
            }
            return $data;
        } else {
            return array();
        }
    }

    public function ajaxCount()
    {
        $data = $this->cache($this->cache_name('invoice_count'), 86400, 'invoice')->count();
        return $data;
    }

    public function ajaxList()
    {
        $data = $this->cache($this->cache_name('invoice_list'), 86400, 'invoice')->page($this->param ['page'], $this->param ['limit'])->order($this->param ['_o'], $this->param ['_b'])->select();
        if ($data) {
            $data = $data->toArray();
            if (!isset ($this->param ['no_need_invoice_handle'])) {
                foreach ($data as $key => $val) {
                    $data [$key] = $this->handleData($val);
                }
            }
            return $data;
        } else {
            return array();
        }
    }

    public function ajaxSearch()
    {
        $data = $this->order($this->param ['_o'], $this->param ['_b'])->select();
        if ($data) {
            $data = $data->toArray();
            if (!isset ($this->param ['no_need_invoice_handle'])) {
                foreach ($data as $key => $val) {
                    $data [$key] = $this->handleData($val);
                }
            }
            return $data;
        } else {
            return array();
        }
    }

    public function ajaxPage()
    {
        $return ['data'] = $this->ajaxList();
        $return ['count'] = $this->ajaxCount();
        return $return;
    }

    public function ajaxSelect()
    {
        $data = $this->cache($this->cache_name('invoice_select'), 86400, 'invoice')->select();
        if ($data) {
            $data = $data->toArray();
            foreach ($data as $key => $val) {
                $data [$key] = $this->handleData($val);
            }
            return $data;
        } else {
            return array();
        }
    }

    // 确认开票
    public function makeInvoice()
    {
        $data = $this->param;
        $data ['state'] = 2;
        $data ['invoice_time'] = time();
        $this->save($data, [
            'invoice_id' => $this->param ['invoice_id']
        ]);
        // 处理订单开票状态
        $this->param ['state'] = 2;
        $get_invoice_info = $this->ajaxFind();
        $get_order_nos = explode(',', $get_invoice_info ['order_nos']);
        $orderdb = new Orderdb ();
        for ($i = 0; $i < count($get_order_nos); $i++) {
            $orderdb->param ['event'] = 'make_invoice';
            $orderdb->param ['order_no'] = $get_order_nos [$i];
            $orderdb->param ['cart_ids'] = explode(',', $get_invoice_info ['cart_ids']);
            $orderdb->editOrder();
        }
        // 推送发票到军采
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $get_invoice_info ['order_nos'])->find()->toArray();
        $orderdb->where('order_id', $get_order['order_id'])->update(['returncode' => '线下开具成功', 'is_down' => 1]);
        $jun_api = new Api();
        $jun_api->sendInvoiceInfo($get_order['out_order_no']);
        Cache::clear('invoice');
        return 'success';
    }

    // 保存数据
    public function ajaxSave()
    {
        if (isset ($this->param ['invoice_id']) && $this->param ['invoice_id'] != '') {
            // 修改
            $get_invoice = $this->find($this->param['invoice_id'])->toArray();
            $order_no = $get_invoice['order_nos'];
            $data [$this->param ['field']] = $this->param ['value'];
            $this->save($data, [
                'invoice_id' => $this->param ['invoice_id']
            ]);
            // 推送发票
            if (isset($this->param['push_jun']) && $this->param['push_jun'] == 'yes') {
                $orderdb = new Orderdb();
                $get_order = $orderdb->where('order_no', $order_no)->find()->toArray();
                $jun_api = new Api();
                $jun_api->sendInvoiceInfo($get_order['out_order_no']);
            }
        } else {
            // 新增 申请开票
            if (!isset ($this->param ['invoice_money'])) {
                $this->param ['invoice_money'] = $this->param ['order_money'];
            }
            $this->allowField(true)->save($this->param);
        }
        Cache::clear('invoice');
        return 'success';
    }

    // 软删除
    public function ajaxDelete()
    {
        if (isset ($this->param ['invoice_id'])) {
            if (isset ($this->param ['delete']) && $this->param ['delete'] == 'yes') {
                $this->destroy(function ($query) {
                    $query->where('invoice_id', 'IN', $this->param ['invoice_id']);
                }, true);
            } else {
                $this->destroy(function ($query) {
                    $query->where('invoice_id', 'IN', $this->param ['invoice_id']);
                });
            }
            Cache::clear('invoice');
            return 'success';
        }
    }

    // 数据处理
    protected function handleData($val)
    {
        $uploaddb = new Uploaddb ();
        $memberdb = new Memberdb ();
        foreach ($val as $k => $v) {
            $val [$k] = $v;
            switch ($k) {
                //		case 'invoice_duty' :
                //			if ($v == '000011000000000') {
                //				$val ['invoice_duty'] = '';
                //			}
                //			break;
                case 'order_nos' :
                    $orderdb = new Orderdb ();
                    $get_order = $orderdb->where('order_no', $v)->find();
                    if ($get_order) {
                        $get_order = $get_order->toArray();
                        $val['caigou_hetong'] = $get_order['cght'];
                        if ($get_order ['out_order_no']) {
                            $val ['out_order_no'] = $get_order ['out_order_no'];
                        } else {
                            $val ['out_order_no'] = $v;
                        }
                        $val['caigou_invoice_duty'] = $get_order['caigou_invoice_duty'];
                        $supplier_id = $get_order ['supplier_id'];
                        $val ['supplier_name'] = '无';
                        $val ['supplier_picture'] = '';
                        $val['caigou_state'] = $get_order['caigou_state'];
                        if ($get_order['caigou_invoice_pz']) {
                            $val['caigou_invoice_pz_info'] = $uploaddb->getSelect(explode(',', $get_order['caigou_invoice_pz']));
                        } else {
                            $val['caigou_invoice_pz_info'] = [];
                        }
                        if ($supplier_id) {
                            $memberdb = new Memberdb ();
                            $get_member = $memberdb->useGlobalScope(false)->where('member_id', $supplier_id)->find();
                            if ($get_member) {
                                $get_member = $get_member->toArray();
                                $val ['supplier_name'] = $get_member ['supplier_name'];
                                $val ['supplier_picture'] = $get_member ['supplier_picture'];
                            }
                        }
                    } else {
                        $val ['out_order_no'] = $v;
                        $val ['supplier_name'] = '无';
                        $val ['supplier_picture'] = '';
                        $val['caigou_hetong'] = '';
                    }

                    break;
                case 'state' :
                    $val ['hongchong'] = 'no';
                    if ($v == 1) {
                        $val ['state_text'] = '<font style=color:#FFB800>申请中</font>';
                    } elseif ($v == 2) {
                        if ($val ['invoice_proof']) {
                            $val ['state_text'] = '<font style=color:#5FB878>已开票</font>';
                            // 电子发票红冲
                            $val ['hongchong'] = 'yes';
                            /*if ($val ['api_type'] == '026' && date ( 'Y-m' ) == $val ['api_date']) {
                                $val ['hongchong'] = 'yes';
                            }*/
                        } else {
                            $val ['state_text'] = '<font style=color:#5FB878>已申请开票</font>';
                        }
                    } elseif ($v == 3) {
                        $val ['state_text'] = '<font style=color:#5FB878>正在开票</font>';
                    } elseif ($v == 4) {
                        $val ['state_text'] = '<font style=color:#FF5722>发票红冲</font>';
                    } else {
                        $val ['state_text'] = '<font style=color:#FF5722>被驳回</font>';
                    }
                    break;
                case 'cart_ids' :
                    if (isset ($this->param ['need_cart_info']) && $this->param ['need_cart_info'] == 'yes') {
                        $cartdb = new Cartdb ();
                        $cartdb->param ['cart_id'] = explode(',', $v);
                        $cartdb->param ['need_goods_title'] = 'yes';
                        $get_cart = $cartdb->ajaxList();
                        $val ['cart_info'] = $get_cart ['list'];
                    }
                    break;
                case 'builder_type' :
                    if ($v == 1) {
                        $val ['builder_type_text'] = '纸质发票';
                    } else {
                        $val ['builder_type_text'] = '电子发票';
                    }
                    break;
                case 'invoice_type' :
                    if ($v == 1) {
                        $val ['invoice_type_text'] = '普通发票';
                    } elseif ($v == 2) {
                        $val ['invoice_type_text'] = '增值税发票';
                    } elseif ($v == 3) {
                        $val ['builder_type'] = 2;
                        $val ['builder_type_text'] = '电子发票';
                        $val ['invoice_type_text'] = '增值税发票';
                    }
                    break;
                case 'invoice_money' :
                    $val ['invoice_money'] = number_format($val ['invoice_money'] / 100, 2, '.', '');
                    break;
                case 'invoice_proof' :
                    if ($val ['invoice_proof']) {
                        $val ['invoice_proof'] = $uploaddb->getFind($val ['invoice_proof']);
                    }
                    break;
                default :
                    break;
            }
        }
        return $val;
    }
}